document.addEventListener('alpine:init', () => {
    Alpine.data('packageTracker', () => ({
        // 状态
        activeTab: 'scan',
        currentPackage: null,
        matchedBatch: null,
        currentBatch: '',
        batches: [],
        scanPackages: [],
        reportPackages: [],
        batchPackages: [],
        selectedBatchForView: null,
        scanInput: '',
        pasteInput: '',
        newBatchId: '',
        fileImport: null,
        notification: {
            show: false,
            type: 'success',
            message: ''
        },
        batchStats: {
            total: 0,
            scanned: 0,
            unscanned: 0,
            completion: 0
        },
        reportStats: {
            total: 0,
            scanned: 0,
            unscanned: 0,
            completion: 0
        },
        reportFilters: {
            batch_id: '全部',
            status: '全部'
        },
        selectedScanPackages: [],
        selectedReportPackages: [],
        selectedBatches: [],
        selectAllScan: false,
        selectAllReport: false,
        selectAllBatch: false,
        
        // 选项卡定义
        tabs: [
            { id: 'scan', name: '扫描管理' },
            { id: 'batch', name: '批次管理' },
            { id: 'report', name: '报表管理' }
        ],
        
        // 初始化
        init() {
            this.loadBatches();
            
            // 根据当前URL设置活动选项卡
            const path = window.location.pathname;
            if (path.includes('/scan')) {
                this.activeTab = 'scan';
            } else if (path.includes('/batch')) {
                this.activeTab = 'batch';
            } else if (path.includes('/report')) {
                this.activeTab = 'report';
            }
            
            // 监听文件输入变化
            this.$watch('activeTab', (value) => {
                if (value === 'scan' && this.currentBatch) {
                    this.loadScanPackages();
                } else if (value === 'batch') {
                    this.loadBatches();
                } else if (value === 'report') {
                    this.generateReport();
                }
            });
        },
        
        // 加载批次
        async loadBatches() {
            try {
                const response = await fetch('/api/batches');
                if (!response.ok) {
                    throw new Error('获取批次失败');
                }
                this.batches = await response.json();
            } catch (error) {
                this.showNotification('error', `加载批次失败: ${error.message}`);
            }
        },
        
        // 加载扫描包裹
        async loadScanPackages() {
            if (!this.currentBatch) return;
            
            try {
                const response = await fetch(`/api/packages?batch_id=${this.currentBatch}`);
                if (!response.ok) {
                    throw new Error('获取包裹失败');
                }
                this.scanPackages = await response.json();
                this.updateBatchStats();
            } catch (error) {
                this.showNotification('error', `加载包裹失败: ${error.message}`);
            }
        },
        
        // 更新批次统计
        updateBatchStats() {
            if (!this.currentBatch) return;
            
            const total = this.scanPackages.length;
            const scanned = this.scanPackages.filter(pkg => pkg.status === '已扫描').length;
            
            this.batchStats = {
                total,
                scanned,
                unscanned: total - scanned,
                completion: total > 0 ? Math.round((scanned / total) * 100) : 0
            };
        },
        
        // 切换批次
        async changeBatch() {
            this.loadScanPackages();
        },
        
        // 处理扫描
        async processScan() {
            if (!this.scanInput.trim()) {
                this.showNotification('error', '请输入包裹条码');
                return;
            }
            
            if (!this.currentBatch) {
                this.showNotification('error', '请先选择批次');
                return;
            }
            
            try {
                const response = await fetch('/api/scan', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        package_id: this.scanInput.trim(),
                        batch_id: this.currentBatch,
                        operator: '网页用户'
                    })
                });
                
                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.error || '扫描处理失败');
                }
                
                const result = await response.json();
                
                // 播放音效
                this.playSound('success');
                
                // 更新状态
                this.currentPackage = result.package_id;
                this.matchedBatch = result.matched_batch;
                this.batchStats = result.batch_stats;
                
                // 清空输入
                this.scanInput = '';
                
                // 显示通知
                this.showNotification('success', result.message);
                
                // 重新加载包裹列表
                this.loadScanPackages();
                
            } catch (error) {
                this.playSound('error');
                this.showNotification('error', `扫描失败: ${error.message}`);
            }
        },
        
        // 导入包裹
        async importPackages(type) {
            if (!this.currentBatch) {
                this.showNotification('error', '请先选择批次');
                return;
            }
            
            try {
                let response;
                
                if (type === 'file') {
                    if (!this.fileImport) {
                        this.showNotification('error', '请选择文件');
                        return;
                    }
                    
                    const formData = new FormData();
                    formData.append('file', this.fileImport);
                    formData.append('batch_id', this.currentBatch);
                    
                    response = await fetch('/api/niantie/import', {
                        method: 'POST',
                        body: formData
                    });
                } else if (type === 'paste') {
                    if (!this.pasteInput.trim()) {
                        this.showNotification('error', '请粘贴包裹数据');
                        return;
                    }
                    
                    response = await fetch('/api/niantie/import', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            paste_text: this.pasteInput.trim(),
                            batch_id: this.currentBatch,
                            operator: 'web_user'
                        })
                    });
                }
                
                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.error || '导入失败');
                }
                
                const result = await response.json();
                
                // 清空输入
                if (type === 'paste') {
                    this.pasteInput = '';
                }
                this.fileImport = null;
                document.getElementById('file-import').value = '';
                
                // 显示通知
                this.showNotification('success', result.message);
                
                // 重新加载包裹列表和批次统计
                this.loadScanPackages();
                this.loadBatchStats();
                
            } catch (error) {
                this.showNotification('error', `导入失败: ${error.message}`);
            }
        },
        
        // 处理文件导入
        handleFileImport(event) {
            this.fileImport = event.target.files[0];
        },
        
        // 匹配包裹
        async matchPackages() {
            if (!this.currentBatch) {
                this.showNotification('请先选择批次', 'error');
                return;
            }

            if (!this.pasteInput.trim()) {
                this.showNotification('请输入要匹配的包裹号', 'error');
                return;
            }

            // 解析包裹号
            const packageIds = this.pasteInput.trim().split('\n')
                .map(line => line.trim())
                .filter(line => line);

            try {
                const response = await fetch('/api/match', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        package_ids: packageIds,
                        batch_id: this.currentBatch
                    })
                });

                const data = await response.json();
                if (response.ok) {
                    // 显示匹配结果
                    this.showNotification(data.message, 'success');
                    
                    // 更新包裹列表
                    await this.loadScanPackages();
                    
                    // 清空粘贴框
                    this.pasteInput = '';
                } else {
                    this.showNotification(data.error || '匹配失败', 'error');
                }
            } catch (error) {
                console.error('匹配包裹时出错:', error);
                this.showNotification('匹配包裹时发生错误', 'error');
            }
        },
        
        // 创建批次
        async createBatch() {
            if (!this.newBatchId.trim()) {
                this.showNotification('error', '请输入批次ID');
                return;
            }
            
            try {
                const response = await fetch('/api/batches', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        batch_id: this.newBatchId.trim()
                    })
                });
                
                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.error || '创建批次失败');
                }
                
                const result = await response.json();
                
                // 清空输入
                this.newBatchId = '';
                
                // 显示通知
                this.showNotification('success', result.message);
                
                // 重新加载批次列表
                this.loadBatches();
                
            } catch (error) {
                this.showNotification('error', `创建批次失败: ${error.message}`);
            }
        },
        
        // 删除选中的批次
        async deleteSelectedBatches() {
            if (this.selectedBatches.length === 0) {
                this.showNotification('error', '请选择要删除的批次');
                return;
            }
            
            if (!confirm(`确定要删除选中的 ${this.selectedBatches.length} 个批次吗？这将同时删除批次下的所有包裹！`)) {
                return;
            }
            
            try {
                const promises = this.selectedBatches.map(batchId => 
                    fetch(`/api/batches/${batchId}`, {
                        method: 'DELETE'
                    })
                );
                
                await Promise.all(promises);
                
                // 清空选择
                this.selectedBatches = [];
                this.selectAllBatch = false;
                
                // 显示通知
                this.showNotification('success', '批次删除成功');
                
                // 重新加载批次列表
                this.loadBatches();
                
            } catch (error) {
                this.showNotification('error', `删除批次失败: ${error.message}`);
            }
        },
        
        // 查看批次包裹
        async viewBatchPackages(batchId) {
            this.selectedBatchForView = batchId;
            
            try {
                const response = await fetch(`/api/packages?batch_id=${batchId}`);
                if (!response.ok) {
                    throw new Error('获取包裹失败');
                }
                this.batchPackages = await response.json();
            } catch (error) {
                this.showNotification('error', `加载包裹失败: ${error.message}`);
            }
        },
        
        // 生成报表
        async generateReport() {
            try {
                let url = '/api/packages?';
                const params = new URLSearchParams();
                
                if (this.reportFilters.batch_id !== '全部') {
                    params.append('batch_id', this.reportFilters.batch_id);
                }
                
                if (this.reportFilters.status !== '全部') {
                    params.append('status', this.reportFilters.status);
                }
                
                url += params.toString();
                
                console.log('Generating report with URL:', url);  // 使用console.log替代app.logger
                
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error('获取报表数据失败');
                }
                
                this.reportPackages = await response.json();
                
                // 计算报表统计
                const total = this.reportPackages.length;
                const scanned = this.reportPackages.filter(pkg => pkg.status === '已扫描').length;
                
                this.reportStats = {
                    total,
                    scanned,
                    unscanned: total - scanned,
                    completion: total > 0 ? Math.round((scanned / total) * 100) : 0
                };
                
                console.log('Report stats:', this.reportStats);  // 添加统计信息日志
                
            } catch (error) {
                console.error('Generate report error:', error);  // 添加错误日志
                this.showNotification('error', `生成报表失败: ${error.message}`);
            }
        },
        
        // 导出报表
        async exportReport() {
            try {
                const response = await fetch('/api/export', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        batch_id: this.reportFilters.batch_id,
                        status: this.reportFilters.status
                    })
                });
                
                if (!response.ok) {
                    const error = await response.json();
                    throw new Error(error.error || '导出报表失败');
                }
                
                // 获取文件名
                const contentDisposition = response.headers.get('content-disposition');
                let filename = 'packages_report.csv';
                if (contentDisposition) {
                    const filenameMatch = contentDisposition.match(/filename="?([^"]+)"?/);
                    if (filenameMatch && filenameMatch[1]) {
                        filename = filenameMatch[1];
                    }
                }
                
                // 下载文件
                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.style.display = 'none';
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                
                this.showNotification('success', '报表导出成功');
                
            } catch (error) {
                this.showNotification('error', `导出报表失败: ${error.message}`);
            }
        },
        
        // 删除选中的包裹
        async deleteSelectedPackages(type) {
            const selectedPackages = type === 'scan' ? this.selectedScanPackages : this.selectedReportPackages;
            
            if (selectedPackages.length === 0) {
                this.showNotification('error', '请选择要删除的包裹');
                return;
            }
            
            if (!confirm(`确定要删除选中的 ${selectedPackages.length} 个包裹吗？`)) {
                return;
            }
            
            try {
                const promises = selectedPackages.map(packageId => 
                    fetch(`/api/packages/${packageId}`, {
                        method: 'DELETE'
                    })
                );
                
                await Promise.all(promises);
                
                // 清空选择
                if (type === 'scan') {
                    this.selectedScanPackages = [];
                    this.selectAllScan = false;
                    this.loadScanPackages();
                } else {
                    this.selectedReportPackages = [];
                    this.selectAllReport = false;
                    this.generateReport();
                }
                
                // 显示通知
                this.showNotification('success', '包裹删除成功');
                
                // 重新加载批次列表（更新统计信息）
                this.loadBatches();
                
            } catch (error) {
                this.showNotification('error', `删除包裹失败: ${error.message}`);
            }
        },
        
        // 切换全选包裹
        toggleAllPackages(type) {
            if (type === 'scan') {
                if (this.selectAllScan) {
                    this.selectedScanPackages = this.scanPackages.map(pkg => pkg.package_id);
                } else {
                    this.selectedScanPackages = [];
                }
            } else {
                if (this.selectAllReport) {
                    this.selectedReportPackages = this.reportPackages.map(pkg => pkg.package_id);
                } else {
                    this.selectedReportPackages = [];
                }
            }
        },
        
        // 切换全选批次
        toggleAllBatches() {
            if (this.selectAllBatch) {
                this.selectedBatches = this.batches.map(batch => batch.batch_id);
            } else {
                this.selectedBatches = [];
            }
        },
        
        // 获取完成率样式类
        getCompletionClass(completion) {
            if (completion >= 90) {
                return 'completion-high';
            } else if (completion >= 50) {
                return 'completion-medium';
            } else {
                return 'completion-low';
            }
        },
        
        // 显示通知
        showNotification(type, message) {
            this.notification = {
                show: true,
                type,
                message
            };
            
            // 自动关闭
            setTimeout(() => {
                this.notification.show = false;
            }, 5000);
        },
        
        // 播放音效
        playSound(type) {
            const sound = document.getElementById(type === 'success' ? 'successSound' : 'errorSound');
            if (sound) {
                sound.currentTime = 0;
                sound.play().catch(e => console.error('播放音效失败:', e));
            }
        }
    }));
});
